<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;

class UsersController extends Controller {
    public function __construct() {
        $this->middleware('auth')->except(['show','create','store','index','confirmEmail']);
        $this->middleware('guest')->only('create');
        $this->middleware('throttle:10,60')->only('store');
    }

    public function index(){
        $users = User::paginate(6);
        return view('users.index',compact('users'));
    }

    public function create() {
        return view('users.create');
    }

    public function show(User $user) {
        return view('users.show', compact('user'));
    }
    //注册
    public function store(Request $request) {
        $this->validate($request, [
            'name' => ['required', 'max:50', Rule::unique('users')],
            'email' => ['required', 'email', Rule::unique('users')],
            'password' => ['required', 'confirmed', 'min:6']
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
        $this->sendEmailConfirmationTo($user);
        session()->flash('success','请前往您的邮箱完成账号激活');
        return redirect('/');
    }

    public function edit(User $user) {
        $this->authorize('update',$user);
        return view('users.edit', compact('user'));
    }

    public function update(User $user, Request $request) {
        $this->authorize('update',$user);
        $this->validate($request,[
            'name'=>['required',Rule::unique('users')->ignore($user->id)],
            'password'=>['nullable','confirmed','min:6']
        ]);
        $data = [];
        $data['name'] = $request->name;
        if($request->password){
            $data['password'] = bcrypt($request->password);
        }
        $user->update($data);
        session()->flash('success','用户信息修改成功');
        return redirect()->route('users.show',$user);
    }
    public function destroy(User $user){
        $this->authorize('destroy',$user);
        $user->delete();
        session()->flash('success','删除成功');
        return back();
    }


    protected function sendEmailConfirmationTo($user) {
        $view = 'emails.confirm';
        $data = compact('user');
        $to = $user->email;
        $subject = '感谢注册 Weibo App应用，请确认你的邮箱';
        Mail::send($view,$data,function($message) use ($to,$subject){
            $message->to($to)->subject($subject);
        });
    }

    public function confirmEmail($token){
        $user = User::where('activation_token',$token)->first();
        $user->activated = true;
        $user->activation_token = null;
        $user->save();

        Auth::login($user);
        session()->flash('success','恭喜您，账号激活成功！');
        return redirect()->route('users.show',[$user]);
    }
}
